package com.course.web.view;

import com.course.auth.SecurityUtils;
import com.course.web.page.AdminUI;
import com.course.web.page.TeachUI;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * Created by Justin on 2017/5/18.
 */
@SpringView(name = LoginView.NAME, ui = {AdminUI.class, TeachUI.class})
public class LoginView extends CustomComponent implements View {
    public static final String NAME = "login";

    private final AuthenticationManager authenticationManager;

    @Autowired
    public LoginView(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        FormLayout form = new FormLayout();
        HorizontalLayout action = new HorizontalLayout();
        TextField username = new TextField("Username");
        TextField password = new TextField("Password");
        Button register = new Button("Sign up");
        Button login = new Button("Sign in");
        form.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER);
        form.addComponent(username);
        form.addComponent(password);
        form.addComponent(action);
        action.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER);
        action.addComponent(register);
        action.addComponent(login);
        setCompositionRoot(form);
        setSizeFull();

        form.setWidthUndefined();
        form.setSpacing(true);
        form.setMargin(true);

        register.setEnabled(false);
        login.addClickListener(evt -> login(username.getValue(), password.getValue()));
    }

    private void login(String username, String password) {
        try {
            Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
            SecurityUtils.login(auth);
            getUI().getNavigator().navigateTo("");
        } catch (AuthenticationException e) {
            Notification.show("Login failed");
        }
    }
}
